<template>
  <div class="snow-page">
    <a-layout>
      <a-layout-sider style="min-width: 250px;">
        <div>
          <h4 style="margin: 10px">企业列表<a-input v-model="serachValue" style="width:180px" placeholder="关键字搜索"
              allow-clear />
            <a-button type="primary" @click="InputEvent">
              <template #icon>
                <icon-search />
              </template>
            </a-button>
          </h4>
          <a-tree :data="treeData" :field-names="{
            key: 'id',
            title: 'name',
            children: 'children'
          }" @select="clickTreeNode" style="margin-left: 5px;max-height: 90%;overflow: auto">
            <template #title="{ name }">
              <a-tooltip :content="name">
                <div class="marquee">
                  <icon-common />
                  {{ name }}
                </div>
              </a-tooltip>
            </template>
          </a-tree>
        </div>
      </a-layout-sider>
      <a-layout>
        <a-layout-content>
          <div id="mapContainer" style="width: 100vw; height: 100vh; z-index: 1"></div>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </div>
</template>

<script setup lang="ts">
import { getAllqiyeAPI } from "@/api/modules/qiye/index";
import { onMounted, ref, onUnmounted } from "vue";

const map = ref(null);
// const timer = ref(null);
const serachValue = ref("")

// const searchVal = ref("");

onMounted(() => {
  // 初始化地图
  initMap();
});
onUnmounted(() => {
  // if (timer.value) {
  //   clearInterval(timer.value);
  // }
});

// function searchOnChange() {
//   let arr = [];
//   if (searchVal.value) {
//     for (let i = 0; i < treeData.value.length; i++) {
//       if (treeData.value[i].name.includes(searchVal.value)) {
//         arr.push(treeData.value[i]);
//       }
//     }
//     if (arr.length > 0) {
//       treeData.value = arr;
//     }
//   } else {
//     let obj = {};
//     getAllqiyeAPI(obj).then(res => {
//       treeData.value = generateTreeNodes(res.data);
//     });
//   }
// }

// function selectTree(val) {
//   let obj = optionData.value.filter(e => {
//     return e.id == val[0];
//   });
//   if (obj[0].lon && obj[0].lat) {
//     map.value.centerAndZoom(new T.LngLat(obj[0].lon, obj[0].lat), 13);
//   }
// }

function clickTreeNode(a, extra) {
  console.log(a);
  map.value.centerAndZoom(new T.LngLat(extra.node.data.lon, extra.node.data.lat), 13);

}

function InputEvent() {

  if (serachValue.value) {
    treeData.value = [];
    let arr = [];
    for (let i = 0; i < optionData.value.length; i++) {
      if (optionData.value[i].name.includes(serachValue.value)) {
        arr.push(optionData.value[i])
      }
    }
    treeData.value = generateTreeNodes(arr);
  } else {
    let obj = {}
    getAllqiyeAPI(obj).then(res => {
      treeData.value = generateTreeNodes(res.data);
    })
  }
}

const treeData = ref([]);
const optionData = ref([]);
const initMap = () => {
  //map创建地图实例
  map.value = new T.Map(document.getElementById("mapContainer"));

  // 设置地图中心点和缩放级别
  map.value.centerAndZoom(new T.LngLat(121.42638, 31.63153), 11);

  addMarkers();

  // timer.value = setTimeout(function () {
  //   addMarkers();
  // }, 10000);
};

function generateTreeNodes(data) {
  const nodeMap = new Map();
  const rootNodes = [];

  // First pass: create nodes and store them in a map
  data.forEach(item => {
    const node = {
      id: item.id,
      name: item.name?item.name:item.cq_company_short_name,
      children: [],
      data: item // Store all original data
    };
    nodeMap.set(item.cq_company_code, node);
  });

  // Second pass: build the tree structure
  data.forEach(item => {
    const node = nodeMap.get(item.cq_company_code);
    if (item.cq_parent_code === "0") {
      rootNodes.push(node);
    } else {
      const parentNode = nodeMap.get(item.cq_parent_code);
      if (parentNode) {
        parentNode.children.push(node);
      } else {
        console.warn(`Parent node ${item.cq_parent_code} not found for ${item.cq_company_code}`);
        rootNodes.push(node); // Add to root if parent not found
      }
    }
  });

  return rootNodes;
}

async function addMarkers() {
  let obj = {};
  // 假设你有一个包含标注点位的数组
  let points = [];
  getAllqiyeAPI(obj).then(res => {
    treeData.value = generateTreeNodes(res.data);
    optionData.value = res.data;

    for (let i = 0; i < res.data.length; i++) {
      if (res.data[i].lon && res.data[i].lat) {
        points.push({ lng: res.data[i].lon, lat: res.data[i].lat, name: res.data[i].name?res.data[i].name:res.data[i].cq_company_short_name });
      }
    }

    map.value.clearOverLays();

    points.forEach(point => {
      const position = new T.LngLat(point.lng, point.lat);
      let icon = new T.Icon({
        iconUrl: "./qiye2.png", // 请求图标图片的URL
        iconSize: new T.Point(30, 30), // 图标可视区域的大小
        iconAnchor: new T.Point(30, 30) // 图标的定位锚点
      });
      // 创建文字标注
      const label = new T.Label({
        text: "<b>" + point.name + "</b>", // 替换为你的文字内容
        position: position, // 文字标注的位置，通常与标点图标的位置相同
        offset: new T.Point(-10, -10), // 文字标注相对于标点图标的偏移量
        style: {
          color: "#000", // 文字颜色
          fontSize: "14px", // 文字大小
          fontWeight: "bold" // 文字粗细
        }
      });
      const marker = new T.Marker(position, { icon: icon });
      map.value.addOverLay(marker);
      map.value.addOverLay(label);
    });
  });
}
</script>


<style>
.tdt-bottom .tdt-left {
  display: none !important;
}

.home-map .side1 {
  background-color: #f8f8f8 !important;
}

.ant-tree {
  background: #f8f8f8 !important;
}

.ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected,
.ant-tree .ant-tree-checkbox :not(.exclude-class)>.ant-tree-node-selected :not(.exclude-class) {
  background-color: #74b2e3 !important;
}

.marquee {
  white-space: nowrap;
  /* 确保文本在一行内显示 */
  overflow: hidden;
  /* 隐藏溢出的内容 */
  text-overflow: ellipsis;
  /* 使用打点显示溢出的文本 */
  width: 100%;
  /* 设置宽度，根据需要调整 */
  max-width: 230px;
  /* 最大宽度，根据需要调整 */

  box-sizing: border-box;
  /* 防止宽度计算包含边框和内边距 */
}



/* .ant-tree-node-selected > *:not(img){
  background-color: #74b2e3 !important; 

} */

/* .ant-tree .ant-tree-treenode{
  padding: 0px !important;
} */
</style>